<?php

namespace app\api\service;

use app\api\exception\ForbiddenException;
use app\api\exception\TokenException;
use app\api\lib\enum\ScopeEnum;
use app\api\service\Token as TokenServer;

class Token
{

    public static function needExclusiveScope()
    {
        $scope = TokenServer::getCurrentTokenVar('scope');
        if ($scope == ScopeEnum::User)
        {
            return TRUE;
        }
        else
        {
            throw new ForbiddenException();
        }
    }

    public static function needPrimaryScope()
    {
        $scope = TokenServer::getCurrentTokenVar('scope');
        if ($scope >= ScopeEnum::User)
        {
            return TRUE;
        }
        else
        {
            throw new ForbiddenException();
        }
    }

    public static function needSuperScope()
    {
        $scope = TokenServer::getCurrentTokenVar('scope');
        if ($scope >= ScopeEnum::Super)
        {
            return TRUE;
        }
        else
        {
            throw new ForbiddenException();
        }
    }

    public static function getCurrentTokenVar($key)
    {
        $token = request()->header('token');
        $token_val = cache($token);
        if (!empty($token_val[$key]))
        {
            return $token_val[$key];
        }
        else
        {
            throw new TokenException;
        }
    }

    public static function getCurrentIdentity($keys)
    {
        
    }

    public static function getCurrentUid()
    {
        $uid = static::getCurrentTokenVar('uid');
        $scope = static::getCurrentTokenVar('scope');
        if (ScopeEnum::Super == $scope)
        {
            return input('uid', $uid);
        }
        else
        {
            return $uid;
            ;
        }
    }

    public static function isValidOperate($checked_uid)
    {
        if (static::getCurrentUid() == $checked_uid)
        {
            return true;
        }
        else
        {
            $option = [
                'msg' => '当前用户无法执行该操作',
                'errorCode' => 10003
            ];
            throw new TokenException($option);
        }
    }

    /**
     * 检验token是否存在
     * @param type $token
     * @return boolean
     */
    public static function verifyToken($token)
    {
        if (!empty(cache($token)))
        {
            return true;
        }
        else
        {
            return false;
        }
    }

}
